package org.example.mrrope.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.example.mrrope.dto.R;
import org.example.mrrope.service.*;
import org.example.mrrope.utils.DingUtil;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.*;


@Api(value = "宜搭", tags = {"宜搭生成派工单接口"})
@RestController
@RequestMapping("/api")
@Slf4j
public class YiDaController {
    @Autowired
    private WorkOrderService workOrderService;
    @Autowired
    PackagingWorkOrder packagingWorkOrder;
    @Autowired
    private OwnPackagingWorkOrderService ownPackagingWorkOrder;
    @Autowired
    private OwnRopeWorkOrderService ownRopeWorkOrder;
    @Autowired
    private OwnSewingWorkOrderService ownSewingWorkOrder;
    @Autowired
    private OwnDoKnotWorkOrderService ownDoKnotWorkOrder;
    @Autowired
    Remittance remittance;
    @Autowired
    PurchaseRequisitionService purchaseRequisition;
    @Autowired
    UpdatePurchasingPriceService updatePurchasingPriceService;
    @Autowired
    ProductionScheduleService productionScheduleService;
    @Autowired
    DingUtil dingUtil;
    @Autowired
    UpdateCostPriceService updateCostPriceService;
    @Autowired
    WuLiaoService wuLiaoService;

    @PostMapping("/productionSchedule/upsert")
    @ApiOperation("新增或更新计划单")
    public R upsertProductionSchedule(@RequestParam("soNum") String soNum,
                                      @RequestParam("poNum") String poNum,
                                      @RequestParam("userId") String userId) {
        productionScheduleService.upsertProductionSchedule(soNum, poNum, userId);
        return R.ok("新增或更新计划单成功");
    }

    @PostMapping("/productionSchedule/update")
    @ApiOperation("更新计划单")
    public R updateProductionSchedule(@RequestParam("soNum") String soNum,
                                      @RequestParam("poNum") String poNum,
                                      @RequestParam("userId") String userId,
                                      @RequestParam("JHoid") String JHoid) {
        productionScheduleService.upProductionSchedule(soNum, poNum, userId, JHoid);
        return R.ok("更新计划单成功");
    }

    @PostMapping("/productionSchedule/updatePacking")
    @ApiOperation("更新计划单包装子表")
    public R updatePackingProductionSchedule(@RequestParam("soNum") String soNum) {
        productionScheduleService.supplementPackingProductionSchedule(soNum);
        return R.ok("更新计划单包装子表成功");
    }

    @PostMapping("/workOrder/create")
    @ApiOperation("生成派工单")
    public R workorderCreate(@RequestParam("id") String id,
                             @RequestParam("isPacking") String isPacking,
                             @RequestParam("userId") String userId) {
        log.info("执行 派工单下发");
        workOrderService.getWorkOrder(id, isPacking, userId);
        log.info("测试是否先结束");
        return R.ok("下发派工单成功");
    }

    /**
     * 根据单独工序下发派工单
     *
     * @param id
     * @param work
     * @param userId
     * @return
     */
    @PostMapping("/workOrder/createWorkGonxu")
    @ApiOperation("根据单独工序下发派工单")
    public R createWorkGonxu(@RequestParam("id") String id,
                             @RequestParam("work") String work,
                             @RequestParam("userId") String userId) {
        workOrderService.createWorkGonxu(id, work, userId);
        log.info("测试是否先结束");
        return R.ok("下发派工单成功");
    }

    @PostMapping("/workOrder/RemittanceSetSales")
    @ApiOperation("回款单写入销售订单收款子表")
    public R remittanceSetSales(String id) {
        try {
            remittance.remittanceSetSales(id);
            log.info("测试异步是否执行");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int code = 0;
        if (code != 0) {
            return R.error();
        }
        return R.ok();
    }

    @PostMapping("/workOrder/generatePurchaseRequisitionFromBom")
    @ApiOperation("BOM生成请购单")
    public R generatePurchaseRequisitionFromBom(@RequestParam("id") String id,
                                                @RequestParam("userId") String userId) {
        try {
            purchaseRequisition.generatePurchaseRequisitionFromBom(id, userId);
            log.info("测试异步是否执行");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.ok();
    }

    @PostMapping("/workOrder/generatePackingPurchaseRequisitionFromBom")
    @ApiOperation("BOM更新请购单包装物料")
    public R generatePackingPurchaseRequisitionFromBom(@RequestParam("id") String id,
                                                       @RequestParam("userId") String userId) {
        try {
             purchaseRequisition.generatePackingPurchaseRequisitionFromBom(id, userId);
            log.info("测试异步是否执行");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return R.ok();
    }

    @PostMapping("/workOrder/updatePurchasingPrice")
    @ApiOperation("更新采购价格")
    public R updatePurchasingPrice(String id, String type) {
        int code = 1;
        try {
            if (type.equals("棉纱")) {
                code = updatePurchasingPriceService.updateCottonYarnPurchasingPrice(id, type);
                log.info("测试异步是否执行");
            } else if (type.equals("配件")) {
                code = updatePurchasingPriceService.updateAccessoriesPurchasingPrice(id, type);
                log.info("测试异步是否执行");
            } else if (type.equals("包装")) {
                code = updatePurchasingPriceService.updatePackingMaterialPurchasingPrice(id, type);
                log.info("测试异步是否执行");
            }
            log.info("更新采购价格完成");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (code != 0) {
            return R.error();
        }
        return R.ok();
    }


    @PostMapping("/ownWorkOrder/create")
    @ApiOperation("生成个人派工单")
    public R ownWorkOrder(@RequestParam("id") String id,
                          @RequestParam("type") String type) {
        if (type.equals("Packaging")) {
            log.info("执行 包装车间个人派工单下发");
            ownPackagingWorkOrder.saveOwnPackagingWorkOrder(id);
            log.info("测试异步是否执行");
        }
        if (type.equals("Rope")) {
            log.info("执行 制绳车间个人派工单下发");
            ownRopeWorkOrder.saveOwnRopeWorkOrder(id);
            log.info("测试异步是否执行");
        }
        if (type.equals("DoKnot")) {
            log.info("执行 制结&手工车间个人派工单下发");
            ownDoKnotWorkOrder.saveOwnDoKnotWorkOrder(id);
            log.info("测试异步是否执行");
        }
        if (type.equals("Sewing")) {
            log.info("执行 缝纫车间个人派工单下发");
            ownSewingWorkOrder.saveOwnSewingWorkOrder(id);
            log.info("测试异步是否执行");
        }
        return R.ok("下发个人派工单成功");
    }

    /**
     * 正式接口勿修改
     */
    @PostMapping("/updatePrice")
    @ApiOperation("更新价格")
    public R updatePrice(String sku, String so, String oid, String userId) {
        updateCostPriceService.updateCpCostPrice(sku, so, oid, userId);
        return R.ok();
    }

    @PostMapping("/updateWLVersion/cp")
    @ApiOperation("刷新销售成品")
    public void updateWLVersion(@RequestParam("so") String so) {
        try {
            productionScheduleService.updateWLVersion(so);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/updateWLVersion/baoZhuang")
    @ApiOperation("刷新销售订单-包装成品")
    public void updateWLVersionBaoZhuang(@RequestParam("instanceId") String instanceId) {
        try {
            productionScheduleService.updateWLVersionBaoZhuang(instanceId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/updateBGDVersion")
    @ApiOperation("更新报关单")
    public R updateBGDVersion() throws Exception {
        List<String> s = dingUtil.getYiDaIds("FORM-434F54618CD44D8C9A220DA804F86FEEANNV", "");
        for (int i = 0; i < s.size(); i++) {
            String instanceId = s.get(i);
            JSONObject object = new JSONObject();
            JSONObject search = new JSONObject();
            JSONObject rkdObj = new JSONObject(dingUtil.getYidaById(instanceId));
            search.put("serialNumberField_lup0qelf", rkdObj.get("serialNumberField_lup0qelf"));
//            String rkd = dingUtil.getYidamodifiedTimeGMTById(instanceId);
            String searchReturnData = dingUtil.yiDaSearchReturnData("FORM-434F54618CD44D8C9A220DA804F86FEEANNV", search);
            JSONArray jsonArray = new JSONArray(searchReturnData);
            String rkd = jsonArray.getJSONObject(0).getString("createdTimeGMT");
            DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                    .append(DateTimeFormatter.ISO_LOCAL_DATE)
                    .appendLiteral('T')
                    .append(DateTimeFormatter.ISO_LOCAL_TIME)
                    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
                    .optionalStart()
                    .appendOffsetId()
                    .toFormatter();
            Instant instant = Instant.from(formatter.parse(rkd));
            long timestamp = instant.toEpochMilli();
            object.put("dateField_m5w3fdma", timestamp);
            dingUtil.UpdateYiDa(instanceId, object);
            log.info("更新内销开票单:{}", i);
        }
        return R.ok("更新报关单完成");
    }

    @PostMapping("/updateSzPrice")
    @ApiOperation("更新绳子价格")
    public R updateSzPrice() throws Exception {
        JSONObject searchJo = new JSONObject();
        searchJo.put("radioField_luqtxwda", "正常");
        searchJo.put("selectField_lup8v6zm", "绳子");
        List<String> s = dingUtil.getYiDaIds("FORM-0A11BF74DDA7458A88A98ED8B1957A85YEGT", searchJo.toString());
        for (int i = 0; i < s.size(); i++) {
            String instanceId = s.get(i);
            JSONObject object = new JSONObject();
            JSONObject cgBo = new JSONObject(dingUtil.getYidaById(instanceId));
            double szPrice = 0.0;
            if (cgBo.has("tableField_lx0590nz")) {
                JSONArray tableField_lx0590nz = cgBo.getJSONArray("tableField_lx0590nz");//棉纱
                for (int j = 0; j < tableField_lx0590nz.length(); j++) {
                    JSONObject mszbObj = tableField_lx0590nz.getJSONObject(j);
                    if (mszbObj.has("associationFormField_lx0590nu_id")) {
                        String substring = mszbObj.getString("associationFormField_lx0590nu_id").replaceAll("\\\\", "").substring(1);
                        String msId = new JSONArray(substring.substring(0, substring.length() - 1)).getJSONObject(0).getString("instanceId");
                        JSONObject msBo = new JSONObject(dingUtil.getYidaById(msId));
                        if (msBo.has("numberField_m0ae0tnb") && mszbObj.has("numberField_lx0590nv")) {
                            double msPrice = msBo.getDouble("numberField_m0ae0tnb");
                            double msBL = mszbObj.getDouble("numberField_lx0590nv");
                            double msPrice_use = msPrice * msBL / 100;
                            szPrice += msPrice_use;
                        }
                    }
                }
            }
            object.put("numberField_m0ae0tnb", szPrice);
            dingUtil.UpdateYiDa(instanceId, object);
            log.info("更新绳子物料:{},数据:{}", i, object);
        }
        return R.ok("更新绳子物料完成");
    }


    @PostMapping("/insertWLNoPrice")
    @ApiOperation("新增物料无价格数据")
    public R updateWLPrice() throws Exception {
        JSONObject searchJo = new JSONObject();
        searchJo.put("textField_lupafwsb", "AC");
        String s = dingUtil.yiDaSearchReturnData("FORM-838E6090DF6C4989B6619E9142D87D5AR4JM", searchJo);
        JSONArray bomOneJson = new JSONArray(s);
        Set<String> uniqueWLItems = new HashSet<>();
        for (int i = 0; i < bomOneJson.length(); i++) {
            JSONObject bomJsonObject = bomOneJson.getJSONObject(i).getJSONObject("formData");
            if (bomJsonObject.has("textField_lupafwsb")) {
                String ck = bomJsonObject.getString("selectField_lxvwwbl4");
                if (Objects.equals(ck, "成品仓库")) {
                    String AC = bomJsonObject.getString("textField_lupafwsb");//AChao
                    double num = bomJsonObject.has("numberField_luqsfqzx") ? bomJsonObject.getDouble("numberField_luqsfqzx") : 0.0;//库存数量
                    if (num > 0) {
                        List<String> yiDaIds = dingUtil.getYiDaIds("FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K", "{\"textField_lujgt576\":\"" + AC + "\"}");
                        JSONArray msArray = dingUtil.getInnerTables(yiDaIds.get(0), "FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K", "tableField_lwg8vm75");
                        for (int j = 0; j < msArray.length(); j++) {
                            JSONObject msJsonObject = msArray.getJSONObject(j);
                            if (msJsonObject.has("textField_lwg902p8")) {
                                uniqueWLItems.add(msJsonObject.getString("textField_lwg902p8"));
                            }
                        }
                        JSONArray pjArray = dingUtil.getInnerTables(yiDaIds.get(0), "FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K", "tableField_lvxe56yi");
                        for (int j = 0; j < pjArray.length(); j++) {
                            JSONObject pjJsonObject = pjArray.getJSONObject(j);
                            if (pjJsonObject.has("textField_lujgt59f")) {
                                uniqueWLItems.add(pjJsonObject.getString("textField_lujgt59f"));
                            }
                        }
                        JSONArray bcArray = dingUtil.getInnerTables(yiDaIds.get(0), "FORM-1302BBEC3D914EBAAF95451A6DCE345ARF8K", "tableField_lxvknj7i");
                        for (int j = 0; j < bcArray.length(); j++) {
                            JSONObject bcJsonObject = bcArray.getJSONObject(j);
                            if (bcJsonObject.has("textField_lxvknj79")) {
                                uniqueWLItems.add(bcJsonObject.getString("textField_lxvknj79"));
                            }
                        }
                    }
                }
            }
        }
        log.info("新增物料数量:{}", uniqueWLItems.size());
        int i = 0;
        for (String uniqueWLItem : uniqueWLItems) {
            searchJo.put("textField_lwg986u6", uniqueWLItem);
            String wlList = dingUtil.yiDaSearchReturnData("FORM-0A11BF74DDA7458A88A98ED8B1957A85YEGT", searchJo);
            JSONObject wlItem = new JSONArray(wlList).getJSONObject(0).getJSONObject("formData");
            JSONObject newObject = new JSONObject();
            if (!wlItem.has("numberField_m0ae0tnb") || (wlItem.has("numberField_m0ae0tnb") && wlItem.getDouble("numberField_m0ae0tnb") == 0.0)) {
                newObject.put("textField_m5qigek2", wlItem.has("textField_lwg986u6") ? wlItem.get("textField_lwg986u6") : "");//bianma
                newObject.put("textField_m5qigek3", wlItem.has("textField_lup8v6zn") ? wlItem.get("textField_lup8v6zn") : "");//name
                newObject.put("textField_m5qigek4", wlItem.has("selectField_lup8v6zm") ? wlItem.get("selectField_lup8v6zm") : "");//type
                String res = dingUtil.saveYiDa("FORM-8D82C37BC4114B5B927A079E1E093293XT4I", newObject, "301542264126357287");
                log.info("新增物料result{}", res);
                log.info("新增物料:{},数据:{}", i, newObject);
            }
            i++;
        }
        return R.ok("完成");
    }

    @PostMapping("/updateWLPriceVersion")
    @ApiOperation("刷新物料价格")
    public void updateWLPRiceVersion() {
        try {
            JSONObject searchJo = new JSONObject();
            searchJo.put("textField_lupafwsb", "AC");
            String s = dingUtil.yiDaSearchReturnData("FORM-2EF550E5EFC74A04927F791B7D515E35GTJK", searchJo);
            JSONArray bomOneJson = new JSONArray(s);
            Set<String> uniqueWLItems = new HashSet<>();
            for (int i = 0; i < bomOneJson.length(); i++) {
                JSONObject bomJsonObject = bomOneJson.getJSONObject(i).getJSONObject("formData");
                String instanceId = bomOneJson.getJSONObject(i).getString("formInstanceId");
                Double onexs = bomJsonObject.has("numberField_lwt597ij") ? bomJsonObject.getDouble("numberField_lwt597ij") : 0.0;
                Double tow = bomJsonObject.has("numberField_lwt597ik") ? bomJsonObject.getDouble("numberField_lwt597ik") : 0.0;
                //已下发作业总数
                Double yxfzyl = bomJsonObject.has("numberField_m5f5gz4u") ? bomJsonObject.getDouble("numberField_m5f5gz4u") : 0.0;
                //已上缴总数
                Double yxfsjsl = bomJsonObject.has("numberField_m5f5gz4w") ? bomJsonObject.getDouble("numberField_m5f5gz4w") : 0.0;
                //已入库总数
                Double yrksl = bomJsonObject.has("numberField_m2ucxjgq") ? bomJsonObject.getDouble("numberField_m2ucxjgq") : 0.0;
                JSONObject object = new JSONObject();
                //未下发作业总数
                object.put("numberField_m2ucxjgr",onexs - yxfzyl);
                //未上缴总数
                object.put("numberField_m5f5gz4x",onexs - yxfsjsl);
                //未入库总数
                object.put("numberField_m5f5gz4v",onexs - yrksl);
                dingUtil.UpdateYiDa(instanceId, object);
                log.info("更新数据:{}", i+1);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/updateW/LPriceVersionTow")
    @ApiOperation("传表单ID刷新数据")
    public void updateWLPRiceVersionTow(String uuid) {
        try {
            JSONObject searchJo = new JSONObject();
//            searchJo.put("CreatedTime","[\"2025-07-14 00:00:00\",\"2025-08-01 00:00:00\"]");
//            searchJo.put("selectField_md30xi8l","棉纱仓库");
//            searchJo.put("textField_m2y9fv7z","棉纱仓库");
            searchJo.put("radioField_lz6dkx3n","绳子");
            List<String> s = dingUtil.getYiDaIds(uuid, searchJo.toString());
            int aa = 1;
            for (String instanceId : s) {
                JSONObject object = new JSONObject();
                object.put("selectField_lwiynwx2", "KG");
                dingUtil.UpdateYiDa(instanceId, object);
                log.info("刷新数据----------{}--------", aa++);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


}
